﻿$(document).ready(function () {
    var pathname = window.location.pathname;
    if (pathname == "/newest") {
        GoToNewest();
    } else if (pathname == "/#popular") {
        GoToPopular();
    }

    var loading = '<img src="/Content/ajax-loader.gif" alt="Hled upplysingum" />';

    //foll sem loadast tegar sida lodast
    GetTheGameRating($("h2").html());

    //hax utaf vid vorum ekki ad na ad setja okkar id eda class a suma ActionLinka i razor
    $(".this-game a").addClass("btn btn-danger");
    $("#loginLink").addClass("btn btn-danger btn-large");
    $(".registerButton").addClass("btn btn-danger btn-large");
    $("#registerLink").addClass("btn btn-info btn-large");
    //foll sem loadast tegar sidan er loadud

    $(".game").click(function () {
        //birtir leiki i gangi eftir tvi hvada leikur er klikkad a
        //birtir lika einkun leikja
        //console.log(this.id);
        var game = this.id;
        $("#new-game").attr("href", game);
        $("#games-inprogress").each(function () {
            $(this).empty();
        })
        if (game == "TicTacToe") {
            $("#about-game").text("Mylla (e. Tic Tac Toe) er spilaður á 3x3 borð og " +
                "skiptast leikmenn á að setja annaðhvort 'X' eða 'O' á reiti borðsins og " +
                "sá fyrsti sem nær þremur táknum í röð lárétt lóðrétt eða á ská vinnur leikinn");
        } else if (game == "Kindo") {
            $("#about-game").text("Kindo er borðspil fyrir 4 leikmenn. Markmið leiksins er fyrir" +
                " hvern leikmann að koma kindinni sinni í miðju leikborðs. ");
        }

        // console.log(this.id);
        GetTheActiveGames(this.id);
        GetTheGameRating(this.id);

        $(".this-game").insertAfter(this);
        $(".this-game").fadeToggle(1);

    })

    function GetTheGameRating(theGame) {
        //skilar einkun leiks sem er gefin
        $("#game-rating").html(loading);
        $.ajax({
            type: "GET",
            corntentType: "application/json; charset=utf-8",
            url: "/Home/GetTheGameRating",
            data: { "theGame": theGame },
            dataType: "json",
            success: function (data) {
                //console.log("gamerating " + data[0]);
                $("#game-rating").html(data[0]);
            }
        })
    }
    
    function GetTheActiveGames(theGame) {
        //skilar leikjum sem eru i gangi fer eftir hvad er sent inn
        $("#games-inprogress-nr").html(loading);
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "/Home/GetActiveGames",
            data: { "theGame": theGame },
            dataType: "json",
            success: function (data) {

                $("#games-inprogress").append("<li><span id='game-inprogress-nr'></span> Leikir i gangi</li>");
                $("#game-inprogress-nr").html(data.length);
                
                for (var i in data) {
                    var gameId = data[i].InstanceId;
                    var playerName = data[i].PlayerName;
                    $("#games-inprogress").append("<li class='instance' id=" + gameId + ">" +  "<a href=/" + theGame + "/Index/" + gameId  + ">" + playerName +"</li>");
                    //console.log("Activegames " + playerName);
                    //console.log("InstanceId " + gameId);
                }
            }
        });

    }

    //ser um ad ratea leiki
    $(".rating").click(function GiveRate() {
        //notandi sem aetlar ad gefa einkun, mjog audvelt ad misnota myndi vilja nota @User.Identity.Name en tar sem tetta er ser skjal ta er tad ekki haegt
        var user = $("#user-name").text();
        //leikurinn sem gefa a einkun
        var game = $("h2").html(); 
        //console.log(this.value);
        //console.log(user);
        //console.log(game);
        var sendData = {
            "UserName": user,
            "Value": this.value,
            "TheGame": game
        };
        $.post("/Home/RateGame", sendData, function (data) {
            if (data == "Buin") {
                $(".rating-done").text("Getur ekki aftur!");
                //console.log("haettusu");
            }
            //console.log("einkun gefin til " + game + ": " + data)
            GetTheGameRating($("h2").html());
        });
    });

    function GoToPopular() {
        //skilar notanda a forsiduna ef hann er ekki tar nu tegar og birtir vinsaelustu leiki
        $(".this-game").hide();
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "/Home/GetPopular",
            data: "{}",
            dataType: "json",
            success: function (data) {
                var pathname = window.location.pathname;
                if (pathname != "/") {
                    window.location = "/#popular";
                }
                var mostPopular = data[0].GameName;
                //console.log(data[0].GameName);
                var nowFirst = $(".game").first();
                //console.log(nowFirst);
                nowFirst.attr("id", mostPopular);
                nowFirst.next().attr("id", data[1].GameName);

            }
        });
    }


    $("#Popular").click(function () {
        GoToPopular();
    });

    function GoToNewest() {
        //skilar notanda a forsidu ef hann er ekki tar nu tegar og birtir vinsaelustu leiki
        $(".this-game").hide();
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "/Home/GetNewest",
            data: "{}",
            dataType: "json",
            success: function (data) {
                var pathname = window.location.pathname;
                if (pathname != "/") {
                    document.location = "/#newest";
                }
                var mostPopular = data[0].GameName;
                //console.log(data[0].GameName);
                var nowFirst = $(".game").first();
                //console.log(nowFirst);
                nowFirst.attr("id", mostPopular);
                nowFirst.next().attr("id", data[1].GameName);

            }
        });
    }

    $("#Newest").click(function () {
        GoToNewest();     
    });
    

    $("#search-bar").click(function (event) {
        //console.log($("#GroupId").attr('value'));
        event.preventDefault();
        $(".search-result").html(loading);
        var search = $("#search-text").val();
        $.ajax({
            type: "GET",
            corntentType: "application/json; charset=utf-8",
            url: "/Account/SearchUser",
            data: { "userName": search },
            dataType: "json",
            success: function (data) {
                //console.log(data.UserName);
                $(".search-result").html("");
                if (data.UserName != search) {
                    $(".search-result").append("<strong>Notandi finnst ekki</strong>");
                    return;
                }
                    //$(".search-result").append('<li><a href=/Account/UserProfile?userName=' + member + ' >' + member + ' </a></li>');
                else
                {
                    var member = data.UserName;
                    document.location.href = "/Account/UserProfile?userName=" + member;
  
                }
            }
        })
    });

    $("#search-for-admin").click(function (event) {
        //ser um ad gera notanda ad admin sem leita er eftir
        //console.log("snilld");
        event.preventDefault();
        $(".admin-result").html(loading);
        var search = $("#make-admin").val();
        $.ajax({
            type: "GET",
            corntentType: "application/json; charset=utf-8",
            url: "/Account/SearchUser",
            data: { "userName": search },
            dataType: "json",
            success: function (data) {
                //console.log(data.userName);
                $(".admin-result").html("");
                if (data.UserName != search) {
                    $(".admin-result").append("<strong>Notandi finnst ekki</strong>");
                    return;
                }
                $("#make-admin").val("");

                var sendData = { "userName": search};
                //console.log(sendData);
                $.post("/Account/MakeAdmin", sendData, function (res) {
                    //console.log(res);
                    if (res === "ok") {
                        $(".admin-result").append("<li><strong>" + search + "</strong> hefur verið gerður að kerfisstjóra</li>");
                    } else if (res === "notok") {
                        $(".admin-result").append("<li><strong>" + search + " er nú þegar kerfisstjóri</strong></li>");
                    } else {
                        $(".admin-result").append("<li><strong>Villa kom upp vinsamlegast reyndu aftur</strong></li>");
                    }
                });
            }
        });
    });

//document rdy endar
});

